// src/components/QuizPage.js

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const QuizPage = () => {
  const [question, setQuestion] = useState('');
  const [answer, setAnswer] = useState('');
  const [userAnswer, setUserAnswer] = useState('');
  const [isCorrect, setIsCorrect] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetchRandomQuestion();
  }, []);

  const fetchRandomQuestion = async () => {
    setIsLoading(true);
    try {
      const response = await axios.get('/api/random-question'); // 假设后端API的路由为 '/api/random-question'，用于获取随机问题
      setQuestion(response.data.question);
      setAnswer(response.data.answer);
      setIsCorrect(null);
      setIsLoading(false);
    } catch (error) {
      console.error('Error fetching random question:', error);
      setIsLoading(false);
    }
  };

  const handleAnswerChange = (e) => {
    setUserAnswer(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (userAnswer.trim().toLowerCase() === answer.toLowerCase()) {
      setIsCorrect(true);
    } else {
      setIsCorrect(false);
    }
  };

  const handleNextQuestion = () => {
    setUserAnswer('');
    fetchRandomQuestion();
  };

  return (
    <div>
      <h2>Quiz Page</h2>
      {isLoading ? (
        <p>Loading...</p>
      ) : (
        <div>
          <p>Question: {question}</p>
          <form onSubmit={handleSubmit}>
            <label htmlFor="answer">Answer:</label>
            <input
              type="text"
              id="answer"
              value={userAnswer}
              onChange={handleAnswerChange}
              required
            />
            <button type="submit">Submit</button>
          </form>
          {isCorrect !== null && (
            <p>{isCorrect ? 'Correct!' : 'Incorrect!'}</p>
          )}
          <button onClick={handleNextQuestion}>Next Question</button>
        </div>
      )}
    </div>
  );
};

export default QuizPage;
